<template>
  <view class="api-test-page">
    <!-- 顶部状态栏占位 -->
    <view class="status-bar"></view>
    
    <!-- 页面标题 -->
    <view class="page-header">
      <text class="page-title">API接口对接测试</text>
      <text class="page-subtitle">测试前后端接口对接情况</text>
    </view>

    <!-- 测试分类 -->
    <view class="test-categories">
      <view 
        class="category-item" 
        :class="{ active: currentCategory === category.key }"
        v-for="category in testCategories" 
        :key="category.key"
        @tap="switchCategory(category.key)"
      >
        <text class="category-name">{{ category.name }}</text>
        <text class="category-count">{{ category.count }}</text>
      </view>
    </view>

    <!-- 测试列表 -->
    <view class="test-list">
      <view 
        class="test-item" 
        v-for="test in currentTests" 
        :key="test.key"
        @tap="runTest(test)"
      >
        <view class="test-header">
          <view class="test-info">
            <text class="test-name">{{ test.name }}</text>
            <text class="test-desc">{{ test.description }}</text>
          </view>
          <view class="test-status" :class="test.status">
            <uni-icons 
              :type="getStatusIcon(test.status)" 
              size="16" 
              :color="getStatusColor(test.status)"
            ></uni-icons>
          </view>
        </view>
        
        <view class="test-details" v-if="test.result">
          <view class="result-item">
            <text class="result-label">状态码:</text>
            <text class="result-value" :class="test.result.success ? 'success' : 'error'">
              {{ test.result.statusCode || 'N/A' }}
            </text>
          </view>
          <view class="result-item">
            <text class="result-label">响应时间:</text>
            <text class="result-value">{{ test.result.duration }}ms</text>
          </view>
          <view class="result-item" v-if="test.result.error">
            <text class="result-label">错误信息:</text>
            <text class="result-value error">{{ test.result.error }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 批量测试按钮 -->
    <view class="batch-test-section">
      <button 
        class="batch-test-btn" 
        @tap="runBatchTest"
        :disabled="isRunning"
      >
        <uni-icons type="loop" size="16" color="#fff"></uni-icons>
        <text>{{ isRunning ? '测试中...' : '批量测试' }}</text>
      </button>
      
      <button 
        class="clear-results-btn" 
        @tap="clearResults"
      >
        <uni-icons type="trash" size="16" color="#667eea"></uni-icons>
        <text>清除结果</text>
      </button>
    </view>

    <!-- 测试统计 -->
    <view class="test-stats">
      <view class="stat-item">
        <text class="stat-label">总测试数</text>
        <text class="stat-value">{{ totalTests }}</text>
      </view>
      <view class="stat-item">
        <text class="stat-label">成功</text>
        <text class="stat-value success">{{ successCount }}</text>
      </view>
      <view class="stat-item">
        <text class="stat-label">失败</text>
        <text class="stat-value error">{{ errorCount }}</text>
      </view>
      <view class="stat-item">
        <text class="stat-label">成功率</text>
        <text class="stat-value">{{ successRate }}%</text>
      </view>
    </view>

    <!-- 底部安全区域 -->
    <view class="bottom-safe"></view>
  </view>
</template>

<script>
import { getGoodsList, getGoodsDetail } from '@/api/goods'
import { getCategoryList } from '@/api/goods/category'
import { getBannerList } from '@/api/goods/banner'
import { getCartList } from '@/api/order/cart'
import { getOrderList } from '@/api/order'
import { getUserInfo } from '@/api/user'
import { getAddressList } from '@/api/user/address'

export default {
  data() {
    return {
      currentCategory: 'goods',
      isRunning: false,
      testCategories: [
        { key: 'goods', name: '商品接口', count: 4 },
        { key: 'user', name: '用户接口', count: 3 },
        { key: 'order', name: '订单接口', count: 3 },
        { key: 'cart', name: '购物车接口', count: 2 }
      ],
      tests: {
        goods: [
          {
            key: 'goods-list',
            name: '商品列表',
            description: '获取商品列表数据',
            status: 'pending',
            run: async () => {
              const startTime = Date.now()
              try {
                const result = await getGoodsList({ page: 1, pageSize: 5 })
                const duration = Date.now() - startTime
                return {
                  success: true,
                  statusCode: 200,
                  duration,
                  data: result
                }
              } catch (error) {
                const duration = Date.now() - startTime
                return {
                  success: false,
                  statusCode: error.statusCode || 500,
                  duration,
                  error: error.message || '请求失败'
                }
              }
            }
          },
          {
            key: 'goods-detail',
            name: '商品详情',
            description: '获取商品详情数据',
            status: 'pending',
            run: async () => {
              const startTime = Date.now()
              try {
                const result = await getGoodsDetail('1')
                const duration = Date.now() - startTime
                return {
                  success: true,
                  statusCode: 200,
                  duration,
                  data: result
                }
              } catch (error) {
                const duration = Date.now() - startTime
                return {
                  success: false,
                  statusCode: error.statusCode || 500,
                  duration,
                  error: error.message || '请求失败'
                }
              }
            }
          },
          {
            key: 'category-list',
            name: '分类列表',
            description: '获取商品分类数据',
            status: 'pending',
            run: async () => {
              const startTime = Date.now()
              try {
                const result = await getCategoryList({ page: 1, pageSize: 10 })
                const duration = Date.now() - startTime
                return {
                  success: true,
                  statusCode: 200,
                  duration,
                  data: result
                }
              } catch (error) {
                const duration = Date.now() - startTime
                return {
                  success: false,
                  statusCode: error.statusCode || 500,
                  duration,
                  error: error.message || '请求失败'
                }
              }
            }
          },
          {
            key: 'banner-list',
            name: '轮播图',
            description: '获取轮播图数据',
            status: 'pending',
            run: async () => {
              const startTime = Date.now()
              try {
                const result = await getBannerList()
                const duration = Date.now() - startTime
                return {
                  success: true,
                  statusCode: 200,
                  duration,
                  data: result
                }
              } catch (error) {
                const duration = Date.now() - startTime
                return {
                  success: false,
                  statusCode: error.statusCode || 500,
                  duration,
                  error: error.message || '请求失败'
                }
              }
            }
          }
        ],
        user: [
          {
            key: 'user-info',
            name: '用户信息',
            description: '获取用户信息',
            status: 'pending',
            run: async () => {
              const startTime = Date.now()
              try {
                const result = await getUserInfo()
                const duration = Date.now() - startTime
                return {
                  success: true,
                  statusCode: 200,
                  duration,
                  data: result
                }
              } catch (error) {
                const duration = Date.now() - startTime
                return {
                  success: false,
                  statusCode: error.statusCode || 500,
                  duration,
                  error: error.message || '请求失败'
                }
              }
            }
          },
          {
            key: 'address-list',
            name: '地址列表',
            description: '获取用户地址列表',
            status: 'pending',
            run: async () => {
              const startTime = Date.now()
              try {
                const result = await getAddressList()
                const duration = Date.now() - startTime
                return {
                  success: true,
                  statusCode: 200,
                  duration,
                  data: result
                }
              } catch (error) {
                const duration = Date.now() - startTime
                return {
                  success: false,
                  statusCode: error.statusCode || 500,
                  duration,
                  error: error.message || '请求失败'
                }
              }
            }
          },
          {
            key: 'user-stats',
            name: '用户统计',
            description: '获取用户统计数据',
            status: 'pending',
            run: async () => {
              const startTime = Date.now()
              try {
                const result = await getUserInfo()
                const duration = Date.now() - startTime
                return {
                  success: true,
                  statusCode: 200,
                  duration,
                  data: result
                }
              } catch (error) {
                const duration = Date.now() - startTime
                return {
                  success: false,
                  statusCode: error.statusCode || 500,
                  duration,
                  error: error.message || '请求失败'
                }
              }
            }
          }
        ],
        order: [
          {
            key: 'order-list',
            name: '订单列表',
            description: '获取订单列表',
            status: 'pending',
            run: async () => {
              const startTime = Date.now()
              try {
                const result = await getOrderList({ page: 1, pageSize: 5 })
                const duration = Date.now() - startTime
                return {
                  success: true,
                  statusCode: 200,
                  duration,
                  data: result
                }
              } catch (error) {
                const duration = Date.now() - startTime
                return {
                  success: false,
                  statusCode: error.statusCode || 500,
                  duration,
                  error: error.message || '请求失败'
                }
              }
            }
          },
          {
            key: 'order-stats',
            name: '订单统计',
            description: '获取订单统计数据',
            status: 'pending',
            run: async () => {
              const startTime = Date.now()
              try {
                const result = await getOrderList({ page: 1, pageSize: 1 })
                const duration = Date.now() - startTime
                return {
                  success: true,
                  statusCode: 200,
                  duration,
                  data: result
                }
              } catch (error) {
                const duration = Date.now() - startTime
                return {
                  success: false,
                  statusCode: error.statusCode || 500,
                  duration,
                  error: error.message || '请求失败'
                }
              }
            }
          },
          {
            key: 'order-detail',
            name: '订单详情',
            description: '获取订单详情',
            status: 'pending',
            run: async () => {
              const startTime = Date.now()
              try {
                const result = await getOrderList({ page: 1, pageSize: 1 })
                const duration = Date.now() - startTime
                return {
                  success: true,
                  statusCode: 200,
                  duration,
                  data: result
                }
              } catch (error) {
                const duration = Date.now() - startTime
                return {
                  success: false,
                  statusCode: error.statusCode || 500,
                  duration,
                  error: error.message || '请求失败'
                }
              }
            }
          }
        ],
        cart: [
          {
            key: 'cart-list',
            name: '购物车列表',
            description: '获取购物车列表',
            status: 'pending',
            run: async () => {
              const startTime = Date.now()
              try {
                const result = await getCartList()
                const duration = Date.now() - startTime
                return {
                  success: true,
                  statusCode: 200,
                  duration,
                  data: result
                }
              } catch (error) {
                const duration = Date.now() - startTime
                return {
                  success: false,
                  statusCode: error.statusCode || 500,
                  duration,
                  error: error.message || '请求失败'
                }
              }
            }
          },
          {
            key: 'cart-stats',
            name: '购物车统计',
            description: '获取购物车统计数据',
            status: 'pending',
            run: async () => {
              const startTime = Date.now()
              try {
                const result = await getCartList()
                const duration = Date.now() - startTime
                return {
                  success: true,
                  statusCode: 200,
                  duration,
                  data: result
                }
              } catch (error) {
                const duration = Date.now() - startTime
                return {
                  success: false,
                  statusCode: error.statusCode || 500,
                  duration,
                  error: error.message || '请求失败'
                }
              }
            }
          }
        ]
      }
    }
  },

  computed: {
    currentTests() {
      return this.tests[this.currentCategory] || []
    },
    
    totalTests() {
      return Object.values(this.tests).flat().length
    },
    
    successCount() {
      return Object.values(this.tests).flat().filter(test => test.status === 'success').length
    },
    
    errorCount() {
      return Object.values(this.tests).flat().filter(test => test.status === 'error').length
    },
    
    successRate() {
      const total = this.totalTests
      return total > 0 ? Math.round((this.successCount / total) * 100) : 0
    }
  },

  methods: {
    switchCategory(category) {
      this.currentCategory = category
    },

    async runTest(test) {
      if (this.isRunning) return
      
      test.status = 'running'
      const result = await test.run()
      test.result = result
      test.status = result.success ? 'success' : 'error'
    },

    async runBatchTest() {
      if (this.isRunning) return
      
      this.isRunning = true
      const allTests = Object.values(this.tests).flat()
      
      for (const test of allTests) {
        await this.runTest(test)
        // 添加延迟避免请求过于频繁
        await new Promise(resolve => setTimeout(resolve, 500))
      }
      
      this.isRunning = false
      
      uni.showToast({
        title: `测试完成，成功率: ${this.successRate}%`,
        icon: 'none',
        duration: 3000
      })
    },

    clearResults() {
      Object.values(this.tests).flat().forEach(test => {
        test.status = 'pending'
        test.result = null
      })
    },

    getStatusIcon(status) {
      const iconMap = {
        pending: 'circle',
        running: 'loop',
        success: 'checkmarkempty',
        error: 'closeempty'
      }
      return iconMap[status] || 'circle'
    },

    getStatusColor(status) {
      const colorMap = {
        pending: '#999',
        running: '#667eea',
        success: '#4ECDC4',
        error: '#FF6B6B'
      }
      return colorMap[status] || '#999'
    }
  }
}
</script>

<style scoped>
.api-test-page {
  min-height: 100vh;
  background: #f8f9fa;
}

.status-bar {
  height: var(--status-bar-height);
  background: #667eea;
}

.page-header {
  background: #667eea;
  padding: 20rpx 30rpx;
  color: #fff;
}

.page-title {
  font-size: 36rpx;
  font-weight: bold;
  display: block;
  margin-bottom: 10rpx;
}

.page-subtitle {
  font-size: 24rpx;
  opacity: 0.8;
}

.test-categories {
  display: flex;
  background: #fff;
  padding: 20rpx;
  border-bottom: 1rpx solid #eee;
}

.category-item {
  flex: 1;
  text-align: center;
  padding: 20rpx;
  border-radius: 12rpx;
  margin: 0 10rpx;
  transition: all 0.3s;
}

.category-item.active {
  background: #667eea;
  color: #fff;
}

.category-name {
  font-size: 28rpx;
  font-weight: bold;
  display: block;
  margin-bottom: 8rpx;
}

.category-count {
  font-size: 20rpx;
  opacity: 0.8;
}

.test-list {
  padding: 20rpx;
}

.test-item {
  background: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
}

.test-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20rpx;
}

.test-info {
  flex: 1;
}

.test-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 8rpx;
}

.test-desc {
  font-size: 24rpx;
  color: #666;
}

.test-status {
  padding: 10rpx;
}

.test-details {
  border-top: 1rpx solid #eee;
  padding-top: 20rpx;
}

.result-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10rpx;
}

.result-label {
  font-size: 24rpx;
  color: #666;
}

.result-value {
  font-size: 24rpx;
  font-weight: bold;
}

.result-value.success {
  color: #4ECDC4;
}

.result-value.error {
  color: #FF6B6B;
}

.batch-test-section {
  padding: 30rpx;
  display: flex;
  gap: 20rpx;
}

.batch-test-btn, .clear-results-btn {
  flex: 1;
  height: 80rpx;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  font-weight: bold;
}

.batch-test-btn {
  background: #667eea;
  color: #fff;
}

.batch-test-btn:disabled {
  background: #ccc;
}

.clear-results-btn {
  background: #fff;
  color: #667eea;
  border: 2rpx solid #667eea;
}

.test-stats {
  background: #fff;
  margin: 0 30rpx 30rpx;
  border-radius: 12rpx;
  padding: 30rpx;
  display: flex;
  justify-content: space-around;
}

.stat-item {
  text-align: center;
}

.stat-label {
  font-size: 24rpx;
  color: #666;
  display: block;
  margin-bottom: 8rpx;
}

.stat-value {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.stat-value.success {
  color: #4ECDC4;
}

.stat-value.error {
  color: #FF6B6B;
}

.bottom-safe {
  height: var(--window-bottom);
}
</style> 